﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Enum;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.IEarTagReposiotry;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using MathNet.Numerics.Differentiation;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace IntelligentAgriculture.Services
{
	/// <summary>
	/// 羊只采购
	/// </summary>
	public class PurchaseFormModelService:IPurchaseFormModelService
	{
		/// <summary>
		/// 采购仓储
		/// </summary>
		private readonly IPurchaseFormModelRepository _purchaseFormModelRepository;
		private readonly ILogger<PurchaseFormModelService> _logger;
		//栋舍
		private readonly IridegRepository _iridegRepository;
		//栏位
		private readonly IColumnManRepository _columnManRepository;
		private readonly IMapper _mapper;
		private readonly AgricultureDbContext _db;
		private readonly IEarTagReposiotry _earTagReposiotry;
		/// <summary>
		/// 养只档案
		/// </summary>
		private readonly ISheepFileModelRepository _shepFileModelRepository;
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="purchaseFormModelRepository"></param>
		public PurchaseFormModelService(IPurchaseFormModelRepository purchaseFormModelRepository, ILogger<PurchaseFormModelService> logger, IMapper mapper, IridegRepository iridegRepository, IColumnManRepository columnManRepository,ISheepFileModelRepository sheepFileModelRepository, AgricultureDbContext db, IEarTagReposiotry earTagReposiotry)
		{
			_purchaseFormModelRepository = purchaseFormModelRepository;
			_logger = logger;
			_mapper = mapper;
			_iridegRepository = iridegRepository;
			_columnManRepository = columnManRepository;
			_shepFileModelRepository = sheepFileModelRepository;
			_db = db;
			_earTagReposiotry = earTagReposiotry;
		}
		/// <summary>
		/// 获取羊只采购列表
		/// </summary>
		/// <returns></returns>
		public async Task<PageOutput<PurchaseformmodelOutOut>> GetPurchaseForms(PurchaseformmodelInPut input)
		{
			try
			{
				var list = await _purchaseFormModelRepository.GetPurchaseForms();
				if (!string.IsNullOrEmpty(input.StartDate))
				{
					list = list.Where(c => c. DateOfPurchase >= DateTime.Parse(input.StartDate));
				}
				if (!string.IsNullOrEmpty(input.EndDate))
				{
					list = list.Where(c => c. DateOfPurchase < DateTime.Parse(input.EndDate).AddDays(1));
				}
				if(input.SheepType>0)
				{
					list = list.Where(c => c. SheepType == input.SheepType);
				}
				if (!string.IsNullOrEmpty(input.Warehouse))
				{
					list = list.Where(c => c. Warehouse == input.Warehouse);
				}
				if(input.BuildingId>0)
				{
					list = list.Where(c => c. BuildingId == input.BuildingId);
				}
				if (!string.IsNullOrEmpty(input.EarTag))
				{
					list = list.Where(c => c. EarTag == input.EarTag);
				}
				if (!string.IsNullOrEmpty(input.CreateBy))
				{
					list = list.Where(c => c. CreateBy == input.CreateBy);
				}
				if (!string.IsNullOrEmpty(input.Document))
				{
					list = list.Where(c => c. Document == input.Document);
				}
				if (input.VendorSnowId > 0)
				{
					list = list.Where(c => c. VendorSnowId == input.VendorSnowId);
				}
				var totalCount = list.Count();

				var pagedQuery = list.OrderByDescending(c => c. CreateTime)
									  .Skip((input.PageIndex - 1) * input.PageSize)
									  .Take(input.PageSize)
									  .ToList();
				var maplist=_mapper.Map<List<PurchaseformmodelOutOut>>(pagedQuery);
				var result = new PageOutput<PurchaseformmodelOutOut>
				{
					TotalCount = totalCount,
					PageSize = input.PageSize,
					Data = maplist
				};

				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError("获取羊只采购列表失败"+ex.Message);
				throw;
			}
		}
		/// <summary>
		/// 羊只采购添加
		/// </summary>
		/// <param name="inPuts"></param>
		/// <returns></returns>
		public async Task<int> AddPurchaseForms(List<PurchaseFormsAddInput> purchaseForms)
		{
			using(var transaction =_db.Database.BeginTransaction())
			{
				try
				{
					var documents = YitIdHelper.NextId().ToString();
					var serialNumbers = YitIdHelper.NextId().ToString();

					// 设置公共属性
					purchaseForms.ForEach(c =>
					{
						c.Document = documents;
						c.SerialNumber = serialNumbers;
						c.BuildingName = _iridegRepository.Showinfo().FirstOrDefault(a => a.RidgepoleId == c.BuildingId).RidgepoleName;
						c.ColumnName = _columnManRepository.GetShow().FirstOrDefault(a => a.ColumnManagementId == c.ColumnId).ColumnName;
						c.CreateTime = DateTime.Now;
						c.CreateBy = "admin";
						c.UpdateTime = DateTime.Now;
						c.UpdateBy = "admin";
						c.IsDel = false;
					});

					// 映射到 Purchaseformmodel
					var purchaseModels = _mapper.Map<List<Purchaseformmodel>>(purchaseForms);

					// 异步添加到 PurchaseFormModelRepository
					await _purchaseFormModelRepository.AddPurchaseForms(purchaseModels);

					// 构建 Sheeprescission 列表
					var sheeprescissions = purchaseForms.Select(item => new Sheeprescission
					{
						SheepRescissionDate = DateTime.Now,
						EarTag = item.EarTag,
						RoundType = 8,
						OutBuildingManageId = null,
						OutColumMangementId = null,
						ToBuildingManageId = item.BuildingId,
						ToColumMangementId = item.ColumnId,
						SheepType = item.SheepType,
						Variety = item.Variety,
						SheepRescissionSex = item.Gender,
						CreateName = item.CreateBy,
						CreateTime = DateTime.Now,
						UpdateName = item.CreateBy,
						UpdateTime = DateTime.Now,
						DocumentNumber = documents,
						Isdel = item.IsDel
					}).ToList();

					// 异步添加到 PurchaseFormModelRepository//转舍
					await _purchaseFormModelRepository.AddPurchaseFormModel(sheeprescissions);

					// 异步添加到 SheepFileModelRepository //羊只档案
					var sheepFileModels = purchaseForms.Select(item => new Sheepfilemodel
					{
						EarTag = item.EarTag,
						Variety = item.Variety,
						SheepSex = item.Gender,
						ElectEarNum = documents,
						AdmissionDate = item.DateOfPurchase,
						BirthPlace = "本场",
						GeneticGrade = 4,
						BirthDate = item.DateOfPurchase,
						BirthState = 1,
						BirthWeight = item.TotalWeight,
						BirthContent = item.PurchaseFormDesc,
						BuildingId = item.BuildingId,
						ColumnId = item.ColumnId,
						SheepType = item.SheepType,
						ProduceLevel = 4,
						SaleLevel = 1,
						IsPregnancy = 0,
						PresentState = 2,
						CreateName = item.CreateBy,
						CreateTime = DateTime.Now,
						UpdateName = item.CreateBy,
						UpdateTime = DateTime.Now,
						IsDel = false,
					}).ToList();
					_shepFileModelRepository.AddListSheepFileModel(sheepFileModels);
					var earTagNumbers = purchaseForms.Select(pf => pf.EarTag).ToList(); // 假设 purchaseForms 是一个包含多个购买表单的集合
					var eartags = await _earTagReposiotry.GetShow();
					var eag = eartags.Where(e => earTagNumbers.Contains(e.EarTagNumber)).ToList();
					eag.ForEach(e => e.EarTagUseStatus = 1);
					transaction.Commit();
					return await _earTagReposiotry.UpdateListAsync(eag); // 批量更新耳
					
				}
				catch (Exception ex)
				{
					transaction.Rollback();
					_logger.LogError("羊只采购添加失败" + ex.Message);
					throw;
				}
					


			}
				
			
		}
		/// <summary>
		/// 获取摘要
		/// </summary>
		/// <returns></returns>
		public async Task<List<object>> GetSummaryEnum()
		{
			try
			{
				List<object> result = new List<object>();
				foreach (var item in System.Enum.GetValues<SummaryEnum>())
				{
					result.Add(new
					{
						name = item.ToString(),
						value = item
					});
				}
				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError("获取摘要失败" + ex.Message);
				throw;
			}
			
		}
		
		/// <summary>
		/// 养只采购删除
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		public async Task<int> DelPurchaseForms(params int[] ids)
		{
			try
			{
				var loginName = "admin";
				return await _purchaseFormModelRepository.DelPurchaseForms(loginName, ids);
			}
			catch (Exception ex)
			{
				_logger.LogError("养只采购删除失败" + ex.Message);
				throw;
			}
		}
		/// <summary>
		/// 反填羊只采购
		/// </summary>
		/// <param name="purchaseFormId"></param>
		/// <returns></returns>
		public async Task<Purchaseformmodel> Purchaseformmodel(int purchaseFormId)
		{
			try
			{
				var pur = await _purchaseFormModelRepository.Purchaseformmodel(purchaseFormId);
				return pur;
			}
			catch (Exception ex)
			{
				_logger.LogError("反填羊只采购失败" + ex.Message);
				throw;
			}
		}
		/// <summary>
		/// 修改羊只采购
		/// </summary>
		/// <param name="entity">实体</param>
		/// <returns></returns>
		public Task<int> UpdatePurchaseformmodel(Purchaseformmodel entity)
		{
			try
			{
				var entitys=_purchaseFormModelRepository.UpdatePurchaseformmodel(entity);
				return entitys;
			}
			catch (Exception ex)
			{
				_logger.LogError("删除羊只采购失败" + ex.Message);
				throw;
			}
		}

	}
}
